package kafkaTest;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Value;

import java.util.Properties;

/**
 * @Classname SimpleProducer
 * @Description TODO
 * @Date 2021/8/2 11:06
 * @Created by bld
 */
public class SimpleProducer {

    @Value("${spring.kafka.topics.topic2}")
    private String topic;

    public static void main(String[] args) throws Exception {

        String topicName = "test";

        // create instance for properties to access producer configs
        Properties props = new Properties();

        //Assign localhost id
        props.put("bootstrap.servers", "localhost:9092");

        //Set acknowledgements for producer requests.
        props.put("acks", "all");

        //If the request fails, the producer can automatically retry,
        props.put("retries", 0);

        //Specify buffer size in config
        props.put("batch.size", 16384);

        //Reduce the no of requests less than 0
        props.put("linger.ms", 1);

        //The buffer.memory controls the total amount of memory available to the producer for buffering.
        props.put("buffer.memory", 33554432);

        props.put("key.serializer",
                "org.apache.kafka.common.serialization.StringSerializer");

        props.put("value.serializer",
                "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer
                <String, String>(props);

        for (int i = 0; i < 1000; i++) {
            String messageStr = "你好，这是第" + i + "条数据";
            System.out.println(messageStr);
            producer.send(new ProducerRecord<String, String>(topicName,
                    Integer.toString(i), messageStr));
        }
        System.out.println("Message sent successfully");
        producer.close();

    }
}
